package com.ayf.payment.game.api.wx;

import com.ayf.payment.game.api.cache.redis.RedisCacheUtil;
import com.ayf.payment.game.api.entity.platform.WxConfig;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author wwl
 * @description:
 * @date 2020/7/31 15:09
 */
@Component
public class WxGatewayConfig {

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    public static String SECRET_KEY="12312qweqAQPa!!!";

    public static String WX_GATEWAY_PATH="http://";

    public static String WX_GATEWAY_URL="/wx/index";

    private static final String PLATFORM_CODE = System.getenv("GAME_AYFPAY_PLATFORM_CODE");

    public static String WX_GATEWAY_TEST_URL=":12345/wx/test";

    /**
     * 获取 access_token
     *
     * @return ACCESS_TOKEN
     */
    public WxGatewayAccessToken getAccessToken(WxConfig wxConfig) {
        //获取当前时间
        long nowTime = System.currentTimeMillis() / 1000;

        WxGatewayAccessToken accessToken = redisCacheUtil.getObjectFromCache("GAME_WX_API_TOKEN_"+wxConfig.getWxOriginId());
        //判断ACCESS_TOKEN是否为空，或者ACCESS_TOKEN_TIME是否超时
        if (accessToken == null) {
            WxGatewayAccessToken  wxAccessTokenNew=new WxGatewayAccessToken();
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxConfig.getAppId() + "&secret=" + wxConfig.getAppSecret();
            LogPortal.info("[{}]获取TOKEN 请求参数：[{}]",wxConfig.getWxOriginId(), url);
            JSONObject jsonObject = WxHttpUtil.doGet("获取TOKEN".concat(wxConfig.getWxOriginId()),url);
            LogPortal.info("[{}]获取TOKEN 返回数据：[{}]",wxConfig.getWxOriginId(), jsonObject.toString());
            //设置ACCESS_TOKEN
            wxAccessTokenNew.setAccessToken(jsonObject.get("access_token").toString());
            //更新ACCESS_TOKEN_TIME
            wxAccessTokenNew.setAccessTokenTime(System.currentTimeMillis() / 1000);
           // ACCESS_TOKEN_MAP.put(wxConfig.getWxOriginId(),wxAccessTokenNew);
            redisCacheUtil.setObjectToCacheDelaySeconds("GAME_WX_API_TOKEN_"+wxConfig.getWxOriginId(),wxAccessTokenNew,7000l);
            return wxAccessTokenNew;
        }
        return accessToken;
    }

    /**
     * 非emoji表情字符判断
     * @param codePoint
     * @return
     */
    private static boolean notisEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) ||
                (codePoint == 0x9) ||
                (codePoint == 0xA) ||
                (codePoint == 0xD) ||
                ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
                ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
    }
    public static boolean containsEmoji(String source) {
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (!notisEmojiCharacter(codePoint)) {
                //判断确认有表情字符
                return true;
            }
        }
        return false;
    }

    public static String filterEmoji(String source) {
        if (!containsEmoji(source)) {
            return source;//如果不包含，直接返回
        }

        StringBuilder buf = null;//该buf保存非emoji的字符
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (notisEmojiCharacter(codePoint)) {
                if (buf == null) {
                    buf = new StringBuilder(source.length());
                }
                buf.append(codePoint);
            }
        }

        if (buf == null) {
            return "";//如果没有找到非emoji的字符，则返回无内容的字符串
        } else {
            if (buf.length() == len) {
                buf = null;
                return source;
            } else {
                return buf.toString();
            }
        }
    }

    /**
     * GM自己动态密保公众号菜单初始化
     * @param wxConfig
     * @param gmId
     * @return
     */
    public boolean setMenu2(WxConfig wxConfig, Integer gmId) {
        try {
            String menuConfig = wxConfig.getMenuConfig();
            String wechatUrl = wxConfig.getNetUrl();
            if (wechatUrl.endsWith("/")){
                wechatUrl=wechatUrl.substring(0,wechatUrl.length()-1);
            }
            menuConfig=menuConfig.replaceAll("@webSiteUrl@",wechatUrl);
            menuConfig=menuConfig.replaceAll("@gmMerchantId@",String.valueOf(gmId));
            menuConfig=menuConfig.replaceAll("@platformCode@",PLATFORM_CODE);
            //获取access_token
            WxGatewayAccessToken accessToken1 = getAccessToken(wxConfig);
            String accessToken = accessToken1.getAccessToken();
            //设置请求
            String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken;
            LogPortal.info("GM自己动态密保公众号菜单初始化 参数[{}]",menuConfig);
            JSONObject jsonObject = WxHttpUtil.doPost("GM自己动态密保公众号菜单初始化".concat(String.valueOf(gmId)),url,menuConfig);
            LogPortal.info("GM自己动态密保公众号菜单初始化成功，接口返回[{}]",jsonObject);
            if (jsonObject != null && 0==jsonObject.getInt("errcode")) {
                return true;
            }
        } catch (Exception e) {
            LogPortal.error("GM自己动态密保公众号菜单初始化-发生[{}]异常,异常信息为[{}]",e,e.getClass().getSimpleName(), e.getMessage());
        }
        return false;
    }

    /**
     * 平台动态密保公众号菜单初始化
     * @param wxConfig
     * @return
     */
    public boolean setMenu3(WxConfig wxConfig) {
        JSONObject big = new JSONObject();
        JSONArray button = new JSONArray();
        try {
            //一级菜单 1
            JSONObject menu_1 = new JSONObject();
            menu_1.put("name", "个人中心");
            JSONArray button_1 = new JSONArray();

            //二级菜单 1
            JSONObject menu_1_1 = new JSONObject();
            menu_1_1.put("name", "回收奖励");
            menu_1_1.put("type", "view");
            menu_1_1.put("url", wxConfig.getNetUrl() + "/pth5/accountBalance");
            button_1.put(menu_1_1);

            //二级菜单 2
            JSONObject menu_1_2 = new JSONObject();
            menu_1_2.put("name", "个人中心");
            menu_1_2.put("type", "view");
            menu_1_2.put("url", wxConfig.getNetUrl() + "/pth5/account");
            button_1.put(menu_1_2);

            menu_1.put("sub_button", button_1);
            button.put(menu_1);

            //一级菜单 3
            JSONObject menu_3 = new JSONObject();
            menu_3.put("name", "联系我们");
            JSONArray button3 = new JSONArray();

            //二级菜单 1
            JSONObject menu_3_1 = new JSONObject();
            menu_3_1.put("name", "联系客服");
            menu_3_1.put("type", "view");
            menu_3_1.put("url", "https://www.aiyoboo.com/static/service_qq.html");
            button3.put(menu_3_1);

            //二级菜单2
            JSONObject menu_3_2 = new JSONObject();
            menu_3_2.put("name", "爱游宝官网");
            menu_3_2.put("type", "view");
            menu_3_2.put("url", "https://www.aiyoboo.com");
            button3.put(menu_3_2);

            menu_3.put("sub_button", button3);
            button.put(menu_3);

            big.put("button", button);
            //获取access_token
            WxGatewayAccessToken accessToken1 = getAccessToken(wxConfig);
            String accessToken = accessToken1.getAccessToken();
            //设置请求
            String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken;
            LogPortal.info("平台动态密保公众号菜单初始化 参数[{}]",big.toString());
            JSONObject jsonObject = WxHttpUtil.doPost("平台动态密保公众号菜单初始化",url, big.toString());
            LogPortal.info("平台动态密保公众号菜单初始化成功，接口返回[{}]",jsonObject);
            if (jsonObject != null && 0==jsonObject.getInt("errcode")) {
                return true;
            }
        } catch (Exception e) {
            LogPortal.error("平台动态密保公众号菜单初始化-发生[{}]异常,异常信息为[{}]",e,e.getClass().getSimpleName(), e.getMessage());
        }
        return false;
    }
}
